package com.sgb.kjwl.view.ui.activity.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySreach4Binding;
import com.sgb.kjwl.di.home.DaggerHomeComponent;
import com.sgb.kjwl.di.home.HomeModule;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.LeaseEvent;
import com.sgb.kjwl.view.ui.fragment.transport.GoodsCarsFragment;
import com.sgb.kjwl.viewmodel.home.SearchModel4;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

/**
 * huwei
 */
public class SearchActivity4 extends AppActivity {
    private static final String TAG = "SearchActivity4";
    private ActivitySreach4Binding binding;
    @Inject
    SearchModel4 viewModel;
    //商品、企业
    public static final int TAB_GOODS = 0;
    public static final int TAB_ENTERPRISE = 1;
    public static final int TAB_GOODS_CARS = 2;
    public static final int TAB_MACHINE_DEVICE = 3;
    public static final String PAGE_FLAG = "page_flag";
    public static final String SEARCH_NAME = "search_name";
    private int currentTab = TAB_GOODS;
    private String[] titles;
    private ArrayList<Fragment> mFragments;
    public static final String SEARCHTYPE_GOODS = "goods";
    public static final String SEARCHTYPE_COMPANY = "company";
    public static final String SEARCHTYPE_LOGISTICS_GOODS = "logistics_goods";
    public static final String SEARCHTYPE_LOGISTICS_CARS = "logistics_car";
    private TextView selectTextView;
    private float unSelectedSize; //默认标题字体大小
    private float selectedSize; //选中时标题栏目字体大小

    public static void start(Context context, boolean isHomePage) {
        Intent intent = new Intent();
        intent.setClass(context, SearchActivity4.class);
        intent.putExtra(PAGE_FLAG, isHomePage);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void start(Context context, boolean isHomePage, String searchName) {
        Intent intent = new Intent();
        intent.setClass(context, SearchActivity4.class);
        intent.putExtra(PAGE_FLAG, isHomePage);
        intent.putExtra(SEARCH_NAME, searchName);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerHomeComponent.builder().appComponent(appComponent).homeModule(new HomeModule(this)).build().inject(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void initView() {
        selectedSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 15, getResources().getDisplayMetrics());
        unSelectedSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 14, getResources().getDisplayMetrics());
        binding = DataBindingUtil.setContentView(SearchActivity4.this, R.layout.activity_sreach4);
        initEtSearchView();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(binding.etView, 0);
                           }
                       },
                200);
    }

    /**
     * 初始化 搜索功能
     */
    private void initEtSearchView() {
        binding.etView.setFocusable(true);
        binding.etView.setFocusableInTouchMode(true);
        binding.etView.requestFocus();
        binding.tvSearch.setOnClickListener(this);
        binding.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.tvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.etView.setText("");
            }
        });
        binding.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    binding.tvSearchDelete.setVisibility(View.GONE);
                } else {
                    binding.tvSearchDelete.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        binding.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(binding.etView.getText().toString())) {
                        MToast.showToast(SearchActivity4.this, "请输入关键字");
                        return true;
                    }
                    doSearch();
                }
                return false;
            }
        });
    }


    private void doSearch() {
        String searchText = binding.etView.getText().toString();
        closeKeybord();
        if (currentTab == TAB_GOODS) {
            EventBus.getDefault().postSticky(LeaseEvent.make().setMessageTag(EventConstant.SEARCH_GOOODS).setMessageData(searchText));
        } else if (currentTab == TAB_ENTERPRISE) {
            EventBus.getDefault().postSticky(LeaseEvent.make().setMessageTag(EventConstant.SEARCH_ENTERPRISE).setMessageData(searchText));
        } else if (currentTab == TAB_GOODS_CARS) {
            EventBus.getDefault().postSticky(LeaseEvent.make().setMessageTag(EventConstant.SEARCH_GOOODS_CARS).setMessageData(searchText));
        } else if (currentTab == TAB_MACHINE_DEVICE) {
            EventBus.getDefault().postSticky(LeaseEvent.make().setMessageTag(EventConstant.SEARCH_DEVICE_MACHINE).setMessageData(searchText));
        }
    }

    @Override
    protected void init() {
        if (mFragments == null) {
            mFragments = new ArrayList<>();
        }
        showTab();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_search:
                finish();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    public void showTab() {
        boolean isHomePage = getIntent().getBooleanExtra(PAGE_FLAG, false);
        if (isHomePage) {
            titles = new String[]{"商品", "企业", "物流"};
        } else {
            titles = new String[]{"商品", "企业",};
        }
        for (int i = 0; i < titles.length; i++) {
            if (i == TAB_GOODS) {
                mFragments.add(SearchFragment.newInstance());
            } else if (i == TAB_ENTERPRISE) {
                mFragments.add(SearchCompanyFragment.newInstance());
            } else {
                mFragments.add(GoodsCarsFragment.newInstance());
            }
        }
        setUpViewPager();
    }

    private void setUpViewPager() {
        SlidingFragmentPagerAdapter mAdapetr = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, titles);
        binding.viewPager.setAdapter(mAdapetr);
        binding.tabLayout.setupWithViewPager(binding.viewPager);
        binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                currentTab = i;
                doSearch();
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        //从上一级进入带入数据进行筛选
        String searchName = getIntent().getStringExtra(SEARCH_NAME);
        if (!TextUtils.isEmpty(searchName)) {
            binding.etView.setText(searchName);
            doSearch();
        }

        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (selectTextView == null)
                    selectTextView = new TextView(getActivity());
                selectTextView.setTextSize(selectedSize);
                selectTextView.setTextColor(getResources().getColor(R.color.color_main));
                selectTextView.setText(tab.getText());
                selectTextView.getPaint().setFakeBoldText(true);
                tab.setCustomView(selectTextView);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                tab.setCustomView(null);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        binding.viewPager.setCurrentItem(0);
        for (int i = 0; i < titles.length; i++) {
            if (i == 0) {
                if (selectTextView == null)
                    selectTextView = new TextView(getActivity());
                selectTextView.setText(titles[i]);
                selectTextView.setTextColor(ContextCompat.getColor(SearchActivity4.this, R.color.color_main));
                selectTextView.getPaint().setFakeBoldText(true);
                selectTextView.setTextSize(selectedSize);
                binding.tabLayout.getTabAt(i).setCustomView(selectTextView);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
